import { View, Text,Image, Input, Textarea } from '@tarojs/components'
import Taro,{ useLoad,useDidShow,useDidHide } from '@tarojs/taro'
import './index.scss'
import { useState } from 'react'
import { AtDivider } from 'taro-ui'
import { request } from "@/utils/request";
import QiWeiQr from '@/components/QiWeiQr'

import UserDialogLogin from "@/components/UserDialogLogin";
import { isLogin } from '@/utils/tools'

export default function H5Task () {
  const [curActivity, setCurActivity] = useState<any>(null);
  // 是不是领取过任务
  const [hasClaimed, setHasClaimed] = useState<boolean>(false)
  
  const [linkText, setLinkText] = useState<string>('')
  const [stepNum, setStepNum] = useState<number>(1)
  const [plugid, setPlugid] = useState<string>('406666362116d3cfe333d714779b3076')
  // 使用二维码跳转到企微
  const [navType, setNavType] = useState<string>('qr')
  const [loginDialogVisible, setLoginDialogVisible] = useState(false);
  const [activityId, setActivityId] = useState<string>('')
  

  // 复制口粮
  function copyToken(){
    if(!isLogin()){
      setLoginDialogVisible(true);
      return 
    }

    Taro.setClipboardData({
      data: curActivity.advertisingCode,
      success: function (res) {
        Taro.showToast({
          title: '复制成功',
          icon: 'success',
          duration: 2000
        })
      }
    })
  }
  function getActivityDetail(activityId) {
    request({
      url: "/api/points/activity/getPointsActivity/" + activityId,
      method: "get",
      success: (activity) => {
        // console.log("getActivityDetail data:", activity);
        activity.detailImageList = activity.detailImage.split(",");
        setCurActivity(activity);
        Taro.setNavigationBarTitle({ title: activity.title });
      },
    });
  }
  function getAdvertisingChannelType(typeStr:string){
    let tgList:string[] = []
    if(typeStr.includes('1')){
      tgList.push('小红书')
    }
    if(typeStr.includes('2')){
      tgList.push('抖音')
    }
    if(tgList.length > 1){
      return tgList.join('、')+'任意发帖'
    }else{
      return tgList.join('')+'发帖'
    }
  }
  // 跳转到h5页面
  function jumpToQw(){
    // 显示企微二维码
  }
  function textareaInput(e:any){
    setLinkText(e.detail.value)
  }
  // 领取积分
  function claimPoints(){
    if(!isLogin()){
      setLoginDialogVisible(true);
      return 
    }
    if(!linkText){
      Taro.showToast({
        title: '请输入链接',
        icon: 'none',
        duration: 2000
      })
      return 
    }
    request({
      url: `/api/points/activity/gainPointsForActivity/${curActivity.id}`,
      method: "post",
      data: {
        activityId: curActivity.id,
        url: linkText
      },
      success: (isClaimed) => {
        if(isClaimed){
          Taro.showToast({
            title: '领取成功',
            icon: 'success',
            duration: 2000
          })
        }else{
          Taro.showToast({
            title: '领取失败',
            icon: 'none',
            duration: 2000
          })
        }
        
      }
    })
  }
  function claimTask(){
    if(!isLogin()){
      setLoginDialogVisible(true);
      return 
    }
    if(!hasClaimed){
      setHasClaimed(true)
      request({
        url: `/api/points/activity/taskClaimed/${curActivity.id}?token=`+Taro.getStorageSync('token'),
        method: "post",
        success: (isClaimed) => {
          if(isClaimed){
            setHasClaimed(true)
            Taro.showToast({
              title: '领取成功',
              icon: 'success',
              duration: 2000
            })
          }else{
            setHasClaimed(false)
            Taro.showToast({
              title: '领取失败',
              icon: 'none',
              duration: 2000
            })
          }
        },
        fail: (err) => {
          setHasClaimed(false)
          Taro.showToast({
            title: '领取失败,请重新领取',
            icon: 'none',
            duration: 2000
          })
        }
      })
    }else {
      Taro.showToast({
        title: '您已经领取过任务了',
        icon: 'none',
        duration: 2000
      })
    }
    
  }
  function loginSuccessCallback() {
    console.log('loginSuccessCallback activityId:',activityId)
    Taro.showToast({
      title: '登录成功',
      icon: 'success',
      duration: 2000
    })

    if (activityId) {
      getActivityDetail(activityId);
    }
  }
  useLoad((options:any) => {
    console.log('useLoad')
    setActivityId(options.activityId)
    if (options.activityId) {
      // 只请求一次就可以
      // getActivityDetail(options.activityId);
    } else {
      Taro.reLaunch({
        url: "/pages/index/index",
      });
    }
  })
  useDidShow(()=>{
    console.log('useDidShow activityId:',activityId)

    if(activityId){
      getActivityDetail(activityId);
    }else {
      let key = '/pages/h5task/index/activityId'
      let storageActivityId = Taro.getStorageSync(key)
      if(storageActivityId){
        getActivityDetail(storageActivityId);
      }
    }
  })
  useDidHide(()=>{
    console.log('useDidHide')
  })

  return (
    curActivity &&
    <View className='h5task'>
      <View className='banner'>
        <Image mode='widthFix' className='image' src={curActivity.coverImage}></Image>
      </View>
      <View className='info'>
        <View className='info-item'>
          <View className='info-item-label'>互助企业</View>
          <View className='info-item-value'>{curActivity.companyName}</View>
        </View>

        <View className='info-item'>
          <View className='info-item-label'>推广类型</View>
          <View className='info-item-value'>{ getAdvertisingChannelType(curActivity.advertisingChannelType)}</View>
        </View>

        <View className='info-item'>
          <View className='info-item-label'>任务奖励</View>
          <View className='info-item-value'>{curActivity.points}分</View>
        </View>

        <View className='info-item'>
          <View className='info-item-label'>剩余数量</View>
          <View className='info-item-value'>{curActivity.remainingCount}</View>
        </View>
      </View>
      <AtDivider content="领取步骤"></AtDivider>
      {
        curActivity.isFriendshipEnabled ? 
        <View className='step-wrap'>
          <View className='step '>
            <View className={['step-title', stepNum >=1 ? 'active': ''].join(' ')}>
              <Text className='dot-num'>1</Text>
              <Text>领取任务</Text>
            </View>
            <View className={['btn','mt64',curActivity.remainingCount <=0 ? 'disabled' : '', hasClaimed ? 'disabled' : ''].join(' ')} onClick={claimTask}>领取任务</View>
          </View>
          <View className='step '>
            <View className={['step-title', stepNum >=2 ? 'active': ''].join(' ')}>
              <Text className='dot-num'>2</Text>
              <Text>长按添加企微客服</Text>
            </View>
            <QiWeiQr></QiWeiQr>
          </View>
        </View> : <View className='step-wrap'>
          <View className='step'>
            <View className={['step-title', stepNum >=1 ? 'active': ''].join(' ')}>
              <Text className='dot-num'>1</Text>
              <Text>首次任务复制口令</Text>
            </View>
            <View className='token'>
              <Text className="token-text">{curActivity.advertisingCode}</Text>
            </View>
            <View className='btn' onClick={copyToken}>复制口令</View>
          </View>
          <View className='step'>
            <View className={['step-title', stepNum >=2 ? 'active': ''].join(' ')}>
              <Text className='dot-num'>2</Text>
              <Text>添加企微好友，粘贴口令并发送</Text>
            </View>
            {
              navType === 'qr' ? <QiWeiQr></QiWeiQr>  : 
              <View className='btn mt64' onClick={jumpToQw}>添加好友</View>
            }
            {/* <View className='qiwei-cell-wrap'>
              <cell className='qiwei-cell' onStartmessage={startmessage} onCompletemessage={completemessage} plugid={plugid}></cell>
            </View> */}
          </View>
        </View> 
      }
      <View className='step'>
        <View className={['step-title', stepNum >= (curActivity.isFriendshipEnabled ? 2 : 3) ? 'active': ''].join(' ')}>
          <Text className='dot-num'>{curActivity.isFriendshipEnabled ? '2' : '3'}</Text>
          <Text>验证</Text>
        </View>
        <View className='input-wrap'>
          <Textarea className='textarea' placeholder='将复制的帖子链接粘贴在这里' value={linkText} onInput={textareaInput}/>
        </View>
        <View className='btn' onClick={claimPoints}>验证</View>
      </View>
      <UserDialogLogin
        visible={loginDialogVisible}
        title="提示"
        content="请先登录"
        btnText="去登录"
        cancel={() => {
          setLoginDialogVisible(false);
        }}
        close={() => {
          setLoginDialogVisible(false);
        }}
        successCallback={loginSuccessCallback}
      ></UserDialogLogin>

    </View>
  )
}
